<template>
  <div class="titleWrap" ref="container">
    <div
      v-for="(t, index) in titles"
      :key="index"
      class="title"
      :class="{ selected: t === selected }"
      @click="checkTitle(t)"
      :ref="
        (el) => {
          if (el) navItems[index] = el;
        }
      "
    >
      {{ t }}
    </div>
  </div>
  <div class="line">
    <div class="indicator" ref="indicator"></div>
  </div>
  <div v-for="(c, index) in defaults" :key="index">
    <component :is="c" v-if="c.props.title === selected" />
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, onUpdated, ref } from "vue";
import Tab from "./Tab.vue";

export default defineComponent({
  props: {
    selected: { type: String, default: "" },
  },
  setup(props, context) {
    const navItems = ref<HTMLDivElement[]>([]);
    const indicator = ref<HTMLDivElement | null>(null);
    const container = ref<HTMLDivElement | null>(null);

    const indicatorFun = () => {
      const divs = navItems.value;
      const result = divs.find((div) => div.classList.contains("selected"));
      const divWidth = result?.getBoundingClientRect().width;
      const divLeft = result?.getBoundingClientRect().left;
      const containerLeft = container.value?.getBoundingClientRect().left;
      if (indicator.value && containerLeft && divLeft) {
        indicator.value.style.width = divWidth + "px";
        indicator.value.style.left = divLeft - containerLeft + "px";
      }
    };
    onMounted(indicatorFun);
    onUpdated(indicatorFun);

    const defaults = context.slots.default?.();

    defaults?.map((tag) => {
      if (tag.type !== Tab) {
        throw new Error("请使用Tab组件");
      }
    });

    const titles = defaults?.map((title) => {
      return title.props?.title;
    });

    const checkTitle = (t: string) => {
      context.emit("update:selected", t);
    };

    return { defaults, titles, checkTitle, navItems, indicator, container };
  },
});
</script>
<style scoped lang="scss">
$color: #5f9ea0;
.titleWrap {
  .title {
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
    transition: color 0.3s;
  }
  .selected {
    color: $color;
  }
}
.line {
  border-bottom: 1px solid grey;
  margin: 10px 0;
  position: relative;
  .indicator {
    position: absolute;
    border: 1px solid $color;
    height: 2px;
    background: $color;
    bottom: 0;
    transition: left 0.3s;
  }
}
</style>
